package com.yfq.springframework.context.support;

import com.sun.istack.internal.Nullable;
import com.yfq.springframework.beans.FactoryBean;
import com.yfq.springframework.beans.InitializingBean;
import com.yfq.springframework.core.convert.ConversionService;
import com.yfq.springframework.core.convert.converter.Converter;
import com.yfq.springframework.core.convert.converter.ConverterFactory;
import com.yfq.springframework.core.convert.converter.GenericConverter;
import com.yfq.springframework.core.convert.support.DefaultConversionService;
import com.yfq.springframework.core.convert.support.GenericConversionService;

import java.util.Set;

/**
 * @author 姚凤桥
 * @date 2023/2/11 12:41
 * @description
 */
public class ConversionServiceFactoryBean implements FactoryBean<ConversionService>, InitializingBean {
    @Nullable
    private Set<?> converters;

    @Nullable
    private GenericConversionService conversionService;

    @Override
    public ConversionService getObject() throws Exception {
        return conversionService;
    }

    @Override
    public Class<?> getObjectType() {
        return conversionService.getClass();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        conversionService = new DefaultConversionService();
        for (Object converter : converters) {
            if (converter instanceof Converter) {
                conversionService.addConverter((Converter<?, ?>) converter);
            } else if (converter instanceof GenericConverter) {
                conversionService.addConverter((GenericConverter) converter);
            } else if (converter instanceof ConverterFactory) {
                conversionService.addConverterFactory((ConverterFactory<?, ?>) converter);
            } else {
                throw new IllegalArgumentException("Each converter object must implement one of the " +
                        "Converter, ConverterFactory, or GenericConverter interfaces");
            }
        }
    }

    public void setConverters(Set<?> converters) {
        this.converters = converters;
    }
}
